package com.jy.task.fileoper;

import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class TcpOper {

	String ip = "";
	String userName = "";
	String psw = "";
	Integer port = 21;

	public TcpOper(String ip, String userName, String psw, Integer port) {
		this.ip = ip;
		this.userName = userName;
		this.port = port != null && port > 0 ? port : 21;
		this.psw = psw;
	}

	/**
	 * 判斷 ftp 是否能连接
	 * 
	 * @return
	 */
	public boolean tcpConnect() {
		boolean result = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(ip, port);
			ftp.login(userName, psw);
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			result = true;
			closeFtp(ftp);// 关闭连接
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	public static void closeFtp(FTPClient ftp) {
		if (ftp != null && ftp.isConnected()) {
			try {
				ftp.logout();
				ftp.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
